// 1. React核心库
import React, { useState, useRef, useCallback } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, message, Space, Tag, Popconfirm, Progress } from 'antd';

// 3. 图标库
import { PlusOutlined, EditOutlined, DeleteOutlined, MessageOutlined, EyeOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable, ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 工具库
import dayjs from 'dayjs';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { AIConversation, AIConversationRequest } from '@/services/generated';

const ConversationList: React.FC = () => {
  const [currentRecord, setCurrentRecord] = useState<AIConversation | null>(null);
  const actionRef = useRef<ActionType>();
  const [loading, setLoading] = useState(false);

  // 删除对话
  const handleDelete = useCallback(async (id: number) => {
    try {
      setLoading(true);
      await autoLoginInDev();
      await apiClients.aiChat.aiChatConversationsDestroy({ id: String(id) });
      message.success('删除成功');
      actionRef.current?.reload();
    } catch (error) {
      message.error('删除失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 表格列定义
  const columns: ProColumns<AIConversation>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      search: false,
    },
    {
      title: '会话标题',
      dataIndex: 'title',
      ellipsis: true,
      formItemProps: {
        rules: [{ required: true, message: '请输入会话标题' }],
      },
    },
    {
      title: 'AI模型',
      dataIndex: 'ai_model_name',
      search: false,
      render: (_, record) => (
        <Tag color="blue">{record.ai_model_name || '未设置'}</Tag>
      ),
    },
    {
      title: 'AI角色',
      dataIndex: 'ai_role_name',
      search: false,
      render: (_, record) => (
        <Tag color="green">{record.ai_role_name || '未设置'}</Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '活跃', status: 'Success' },
        archived: { text: '已归档', status: 'Warning' },
        deleted: { text: '已删除', status: 'Error' },
      },
      render: (_, record) => {
        const statusMap = {
          active: { color: 'green', text: '活跃' },
          archived: { color: 'orange', text: '已归档' },
          deleted: { color: 'red', text: '已删除' },
        };
        const status = statusMap[record.status as keyof typeof statusMap];
        return <Tag color={status?.color}>{status?.text}</Tag>;
      },
    },
    {
      title: '消息数量',
      dataIndex: 'message_count',
      search: false,
      render: (_, record) => (
        <Tag color="purple">{record.message_count || 0} 条</Tag>
      ),
    },
    {
      title: 'Token使用',
      dataIndex: 'used_tokens',
      search: false,
      render: (_, record) => (
        <div style={{ width: 120 }}>
          <div>{record.used_tokens || 0} tokens</div>
          <Progress
            percent={Math.min((Number(record.used_tokens) || 0) / 10000 * 100, 100)}
            size="small"
            showInfo={false}
          />
        </div>
      ),
    },
    {
      title: '最后消息时间',
      dataIndex: 'last_message_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      render: (_, record) => {
        if (!record.last_message_at) return '-';
        const date = dayjs(record.last_message_at);
        return date.isValid() ? date.format('MM-DD HH:mm') : '-';
      },
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      search: false,
      sorter: true,
      render: (_, record) => {
        if (!record.created_at) return '-';
        const date = dayjs(record.created_at);
        return date.isValid() ? date.format('MM-DD HH:mm') : '-';
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 220,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            size="small"
            icon={<MessageOutlined />}
            href={`/ai-chat/conversations/chat/${record.id}`}
          >
            对话
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            href={`/ai-chat/conversations/detail/${record.id}`}
          >
            详情
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            href={`/ai-chat/conversations/edit/${record.id}`}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个对话吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              loading={loading}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: 'AI对话管理',
        subTitle: '管理AI对话会话',
      }}
    >
      <ProTable<AIConversation>
           scroll={{x: 'max-content'}}
        headerTitle="对话会话列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            href="/ai-chat/conversations/create"
          >
            新建对话
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          try {
            await autoLoginInDev();
            const response = await apiClients.aiChat.aiChatConversationsList({
              page: params.current || 1,
              pageSize: params.pageSize || 20,
              search: params.title, // 搜索参数
              status: params.status, // 过滤参数
              aiModel: params.ai_model, // 过滤参数
              aiRole: params.ai_role, // 过滤参数
              ordering: sort && Object.keys(sort).length > 0 ?
                Object.entries(sort).map(([key, value]) => value === 'ascend' ? key : `-${key}`).join(',') :
                undefined, // 排序参数
            });
            return {
              data: response.data?.items || [],
              success: true,
              total: response.data?.total || 0
            };
          } catch (error) {
            message.error('获取数据失败');
            return { data: [], success: false, total: 0 };
          }
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default ConversationList;
